/*
 * Copyright 2018 the original author or authors.
 *
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 *
 *
 *
 *
 */

package org.liang.javasource.factory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import org.liang.javasource.bean.BeanInfo;
import org.liang.javasource.util.TemplateUtil;
import freemarker.template.Template;

/**
 * 根据类信息，生成javasource源码模板类
 * 
 * @author houliang
 * @date 2018年3月5日
 */
public abstract class BeanFactory {

	public static void generateBean(BeanInfo beanInfo) {
		if (beanInfo == null) {
			return;
		}
		try {
			String outPath = beanInfo.getClassPath() + "\\"
					+ beanInfo.getClassPackage().replace(".", "\\") + "\\"
					+ beanInfo.getClassName() + ".java";
			File file = new File(outPath);

			checkParentDir(file.getParent());// 创建父目录

			// 如果文件存在，并且不覆盖，不操作
			if (file.exists()) {
				if (beanInfo.cover) {
					FileOutputStream f = new FileOutputStream(outPath);
					Writer out = new OutputStreamWriter(f);
					Template template = TemplateUtil
							.getTemplate("javaBean.ftl");
					template.process(beanInfo, out);
					System.err.println("文件已存在，覆盖操作：" + outPath);
				} else {
					System.err.println("文件已存在，不生成：" + outPath);
				}
			} else {
				FileOutputStream f = new FileOutputStream(outPath);
				Writer out = new OutputStreamWriter(f);
				Template template = TemplateUtil.getTemplate("javaBean.ftl");
				template.process(beanInfo, out);
				System.out.println("文件新建路径：" + file.getAbsolutePath());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 校验路径是否存在，不存在创建
	 */
	private static void checkParentDir(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static void generateBeans(List<BeanInfo> beanInfo) {
		if (beanInfo == null) {
			return;
		}
		try {
			for (BeanInfo beanInfo2 : beanInfo) {
				generateBean(beanInfo2);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void printBean(BeanInfo beanInfo) {
		if (beanInfo == null) {
			return;
		}
		try {
			Writer out = new OutputStreamWriter(System.out);
			Template template = TemplateUtil.getTemplate("javaBean.ftl");
			template.process(beanInfo, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void printBeans(List<BeanInfo> beanInfo) {
		if (beanInfo == null) {
			return;
		}
		try {
			for (BeanInfo beanInfo2 : beanInfo) {
				printBean(beanInfo2);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
